#include "timeutils.h"
#include <QtEndian>
QByteArray TimeUtils::getCurrentTimeAsBinary()
{
    QDateTime now = QDateTime::currentDateTime();
    QDate date = now.date();
    QTime time = now.time();

    quint8 year = static_cast<quint8>(date.year() % 100); // 后两位年份
    quint8 month = static_cast<quint8>(date.month());
    quint8 day = static_cast<quint8>(date.day());
    quint8 hour = static_cast<quint8>(time.hour());
    quint8 minute = static_cast<quint8>(time.minute());
    quint8 second = static_cast<quint8>(time.second());

    QByteArray data;
    data.append(QByteArray(reinterpret_cast<const char*>(&year), 1));
    data.append(QByteArray(reinterpret_cast<const char*>(&month), 1));
    data.append(QByteArray(reinterpret_cast<const char*>(&day), 1));
    data.append(QByteArray(reinterpret_cast<const char*>(&hour), 1));
    data.append(QByteArray(reinterpret_cast<const char*>(&minute), 1));
    data.append(QByteArray(reinterpret_cast<const char*>(&second), 1));

    return data;
}

// 时间转换
QString TimeUtils::parseHexToDateTimeString(const QByteArray& data)
{
    if (data.size() != 6) {
        return QString("数据长度错误");
    }

    quint8 year = static_cast<quint8>(data[0]);
    quint8 month = static_cast<quint8>(data[1]);
    quint8 day = static_cast<quint8>(data[2]);
    quint8 hour = static_cast<quint8>(data[3]);
    quint8 minute = static_cast<quint8>(data[4]);
    quint8 second = static_cast<quint8>(data[5]);

    int fullYear = 2000 + year;

    QDate date(fullYear, month, day);
    QTime time(hour, minute, second);

    if (!date.isValid() || !time.isValid()) {
        return QString("无效的日期时间");
    }

    QDateTime dt = QDateTime(date, time);
    return dt.toString("yyyy-MM-dd HH:mm:ss");
}

// 转换IP
QString TimeUtils::hexToIp(const QString& hexStr)
{
    if (hexStr.length() != 8) return "无效IP";

    QByteArray ipBytes = QByteArray::fromHex(hexStr.toUtf8());
    if (ipBytes.size() != 4) return "无效IP";

    const quint8* bytes = reinterpret_cast<const quint8*>(ipBytes.constData());
    return QString("%1.%2.%3.%4")
        .arg(bytes[0]).arg(bytes[1]).arg(bytes[2]).arg(bytes[3]);
}

quint16 TimeUtils::convertLittleEndianToPort(const QByteArray& data)
{
    if (data.size() != 2) {
        qWarning() << "数据长度错误，应为2个字节";
        return 0;
    }

    // 使用 Qt 的 fromLittleEndian 函数直接转换
    return static_cast<quint16>(qFromLittleEndian<quint16>(reinterpret_cast<const uchar*>(data.data())));
}

double TimeUtils::hexToVoltage(const QString& hexStr)
{
    //qDebug() << "hexStr" << hexStr;
    if (hexStr.length() != 8) {
        qDebug() << "错误：电压数据必须是 8 个字符";
        return 0.0;
    }
    QByteArray byteArray = QByteArray::fromHex(hexStr.toUtf8());
    if (byteArray.size() != 4) {
        qDebug() << "错误：电压数据必须是 4 字节（8 个字符）";
        return 0.0;
    }
    // 正确方式：使用 qFromLittleEndian 强制按小端解析
    quint32 value = qFromLittleEndian<quint32>((const uchar*)byteArray.constData());
    //qDebug() << "value" << value;
    double voltage = static_cast<double>(value) / 1000.0;
    return voltage;
}

double TimeUtils::hexToValue_LittleEndian(const QString& hexStr)
{
    qDebug() << "开始解析输入 HEX：" << hexStr;
    if (hexStr.length() != 4) {
        qDebug() << "错误：输入必须是 4 个字符的十六进制字符串";
        return 0.0;
    }
    // 转换为字节数组
    QByteArray byteArray = QByteArray::fromHex(hexStr.toUtf8());
    qDebug() << "原始字节（QByteArray）：" << byteArray;
    qDebug() << "原始字节（toHex）：" << byteArray.toHex();
    if (byteArray.size() != 2) {
        qDebug() << "错误：转换后的字节长度不为 2";
        return 0.0;
    }
    // 反转字节顺序（大端 -> 小端）
    std::reverse(byteArray.begin(), byteArray.end());
    qDebug() << "反转后字节（toHex）：" << byteArray.toHex();
    // 使用 qFromLittleEndian 解析为 quint16
    quint16 value = qFromLittleEndian<quint16>((const uchar*)byteArray.constData());
    qDebug() << "解析出的十进制值：" << value;
    // 转成 double 并除以 100
    double result = static_cast<double>(value) / 100.0;
    qDebug() << "最终结果（除以 100）：" << result;
    qDebug() << "解析完成\n";
    return result;
}

QByteArray TimeUtils::ipStringToByteArray(const QString& ipStr)
{
    QStringList parts = ipStr.split('.');
    if (parts.size() != 4) {
        qDebug() << "Invalid IP format.";
        return QByteArray();
    }
    QByteArray data;
    for (const QString& part : parts) {
        bool ok;
        quint8 byte = static_cast<quint8>(part.toInt(&ok));
        if (!ok || byte > 255) {
            qDebug() << "Invalid IP part:" << part;
            return QByteArray();
        }
        data.append(static_cast<char>(byte));
    }
    return data; // 4 bytes, e.g. \xC0\xA8\x00\x10
}
